<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/12/4
 * Time: 10:36
 */

namespace App\Extend\SysExtend\Template;


use App\Extend\SysExtend\Helper;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Template\Render;
use EasySwoole\Template\RenderInterface;
use think\Template;

class TpTemplate implements RenderInterface
{
    private $tp_temp;
    
    private $config = [
        // 模板路径
        'view_path'	    =>	EASYSWOOLE_ROOT . '/App/View/',
        // 模板缓存路径
        'cache_path'	=>	EASYSWOOLE_ROOT . '/Temp/Template/',
    ];

    /**
     * 注册驱动
     */
    public static function register()
    {
        Render::getInstance()->getConfig()->setRender(new self());
        Render::getInstance()->getConfig()->setTempDir(EASYSWOOLE_TEMP_DIR);
        Render::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer());
    }

    public function __construct()
    {
        if($config = Helper::config('template')) {
            $this->config = $config;
        }
        $this->tp_temp = new Template($this->config);
    }
    
    public function render(string $template, array $data = [], array $options = []): ?string
    {
        // TODO: Implement render() method.
        // 把助手函数类放入变量中
        $data['_tph'] = 'App\\Extend\\SysExtend\\Template\\TemplateHelper';
        ob_start();
        $this->tp_temp->fetch($template,$data);
        return ob_get_clean();
    }

    public function afterRender(?string $result, string $template, array $data = [], array $options = [])
    {
        // TODO: Implement afterRender() method.
    }

    public function onException(\Throwable $throwable): string
    {
        // TODO: Implement onException() method.
        $msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}";
        trigger_error($msg);
        return $msg;
    }
}